import Vue from 'vue'
import store from './store/index'
import FastClick from 'fastclick'
import VueRouter from 'vue-router'
import App from './App.vue'
import {AppRouter} from './router/index'
import VueScroller from 'vue-scroller'
import {ToastPlugin, ConfirmPlugin, AlertPlugin, LoadingPlugin, ConfigPlugin} from 'Vux'
Vue.use(ConfigPlugin, {
  $layout: 'VIEW_BOX'
})
Vue.use(ConfirmPlugin);
Vue.use(LoadingPlugin);
Vue.use(ToastPlugin);
Vue.use(AlertPlugin);
Vue.use(VueScroller);
// 或者umd方式
// 引入构建的js文件

Vue.use(VueRouter);
const RouterConfig = {
  routes: AppRouter
};
const router = new VueRouter(RouterConfig);

FastClick.attach(document.body);

Vue.config.productionTip = false;

router.beforeEach((r_to, r_from, next) => {
  let ios = window.navigator.userAgent.toLowerCase().match(/iPhone/i);
  let android = window.navigator.userAgent.toLowerCase().match(/android/i);
  if (ios) {
    store.dispatch('getIos', true)
  } else if (android) {
    store.dispatch('getIos', false)
  }
  const getLoginInfo = () => {
    if (store.state.app.workNumber || store.state.app.loginInfo) {
      return
    } else {
      $.get("../api/getLoginInfo", {}, (data) => {
        if (data.code === 400) {
          return
        }
        store.dispatch('getWeChat', data.weChatId);
        store.dispatch('getWorkNumber', data.workNumber)
      }, 'json')
    }
  };

  function isWeiXin() {
    let ua = window.navigator.userAgent.toLowerCase();
    if (ua.match(/micromessenger/i)) {
      return true;
    } else {
      return true;
    }
  }

  getLoginInfo();
  const to = r_to.path;
  const from = r_from.path;
  let url = location.search; //获取url中"?"符后的字串
  let theRequest = new Object();
  let weChatId = null;
  if (url.indexOf("?") !== -1) {
    let str = url.substr(0, url.indexOf('&'));
    if (str !== "") {
      weChatId = str.substr(str.indexOf('=') + 1);
    } else {
      weChatId = url.substr(url.indexOf('=') + 1);
    }
    theRequest["wechatid"] = weChatId;
  }
  if (!isWeiXin()) {
    alert("当前页面无法在浏览器上打开");
    return
  } else {
    let flag = store.state.app.weChatCode;
    if (to === '/' && theRequest.wechatid) {
      store.dispatch('getWeChat', theRequest.wechatid);
      $.get('../api/home?weChatId=' + theRequest.wechatid, {}, (data) => {
        if (data.code === 200) {
          next({path: '/home'});
          store.dispatch('getWorkNumber', data.loginFlag)
        } else {
          next({path: '/login'})
        }
      }, "json");
    } else if (to === '/') {
      alert("当前URL解析错误,缺失wxId");
    } else {
      if (flag !== null) {
        next()
      } else {
        next({path: '/'})
      }
    }
  }
  // 定制某些页面的切换方向
  if (to === '/home') {
    store.dispatch('initForm');
    next()
  }
});
router.afterEach(() => {
  window.scrollTo(0, 0);
});

/* eslint-disable no-new */
new Vue({
  store,
  router,
  render: h => h(App)
}).$mount('#app-box');
